package com.china.zhuoyue.api.core

import android.util.Log
import com.china.zhuoyue.api.core.adapter.CoreCallAdapterFactory
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.fastjson.FastJsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit


val MOSHI = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

/**
 *   @auther : zhoucl
 *   time   : 2017/09/04
 */
object ApiHelper {
    private const val TIME_OUT = 60L
    private val mRetrofit: Retrofit by lazy {
        Retrofit.Builder()
            .client(getOkHttpClient(TIME_OUT))
//            .addConverterFactory(MoshiConverterFactory.create(MOSHI))
            .addConverterFactory(FastJsonConverterFactory.create())
            .addCallAdapterFactory(CoreCallAdapterFactory.create(WrapResultBean::class.java))
            .baseUrl(BuildConfig.BASE_URL)
            .build()
    }

    fun <T> create(clazz: Class<T>): T = mRetrofit.create(clazz)

    private fun getOkHttpClient(timeout: Long): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(timeout, TimeUnit.SECONDS)
            .writeTimeout(timeout, TimeUnit.SECONDS)
            .readTimeout(timeout, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
            .addInterceptor(ConvertInterceptor())
            .apply {
                if (BuildConfig.DEBUG) {
                    addInterceptor(getHttpLoggingInterceptor())
                }
            }
            .connectionPool(ConnectionPool(8, 15, TimeUnit.SECONDS))
            .build()
    }

    private fun getHttpLoggingInterceptor() =
        HttpLoggingInterceptor { Log.e("Logger", "Api请求==>$it") }.apply { setLevel(HttpLoggingInterceptor.Level.BODY) }
}